package com.manyi.ihouse.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

/**
  * 无视Https证书是否正确的Java Http Client
  */
public class HttpsUtil {

    /**
     * 忽视证书HostName
     */
    private static HostnameVerifier ignoreHostnameVerifier         = new HostnameVerifier() {
                                                                       @Override
                                                                    public boolean verify(String s,
                                                                                             SSLSession sslsession) {
                                                                           System.out
                                                                               .println("WARNING: Hostname is not matched for cert.");
                                                                           return true;
                                                                       }
                                                                   };

    /**
    * Ignore Certification
    */
    private static TrustManager     ignoreCertificationTrustManger = new X509TrustManager() {

                                                                       private X509Certificate[] certificates;

                                                                       @Override
                                                                    public void checkClientTrusted(X509Certificate certificates[],
                                                                                                      String authType)
                                                                                                                      throws CertificateException {
                                                                           if (this.certificates == null) {
                                                                               this.certificates = certificates;
                                                                               System.out
                                                                                   .println("init at checkClientTrusted");
                                                                           }

                                                                       }

                                                                       @Override
                                                                    public void checkServerTrusted(X509Certificate[] ax509certificate,
                                                                                                      String s)
                                                                                                               throws CertificateException {
                                                                           if (this.certificates == null) {
                                                                               this.certificates = ax509certificate;
                                                                           }

                                                                           //            for (int c = 0; c < certificates.length; c++) {
                                                                           //                X509Certificate cert = certificates[c];
                                                                           //                System.out.println(" Server certificate " + (c + 1) + ":");
                                                                           //                System.out.println("  Subject DN: " + cert.getSubjectDN());
                                                                           //                System.out.println("  Signature Algorithm: "
                                                                           //                        + cert.getSigAlgName());
                                                                           //                System.out.println("  Valid from: " + cert.getNotBefore());
                                                                           //                System.out.println("  Valid until: " + cert.getNotAfter());
                                                                           //                System.out.println("  Issuer: " + cert.getIssuerDN());
                                                                           //            }

                                                                       }

                                                                       @Override
                                                                    public X509Certificate[] getAcceptedIssuers() {
                                                                           // TODO Auto-generated method stub
                                                                           return null;
                                                                       }

                                                                   };

    //上海请求                                                             
    public static String getShHttps(String urlString) {

        ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
        try {

            URL url = new URL(urlString);

            /*
             * use ignore host name verifier
             */
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestProperty("Host", "soa.dooioo.com");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("device_id",
                "d5521062470a0e6bcc09dcd5db30ca58656596a847bd3a85b55af86b483e2f16");
            connection.setRequestProperty("Lianjia-CityCode", "sh");
            connection.setRequestProperty("Lianjia-Device-Id",
                "914FFEF9-D45F-4D71-8AFB-8C3FD511E547");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("User-Agent", "App_version_2.1.0;iOS;");

            connection.setRequestProperty("Accept-Language", "zh-Hans-CN;q=1");
            connection.setRequestProperty("Lianjia-Client", "ios");
            connection.setRequestProperty("Authorization", "Bearer 7poanTTBCymmgE0FOn1oKp");
            connection.setRequestProperty("cityCode", "sh");
            connection.setRequestProperty("client", "ios");
            connection.setRequestProperty("version", "510");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("contentType", "utf-8");
            // Prepare SSL Context
            TrustManager[] tm = { ignoreCertificationTrustManger };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);

            InputStream reader = connection.getInputStream();
            byte[] bytes = new byte[512];
            int length = reader.read(bytes);

            do {
                buffer.write(bytes, 0, length);
                length = reader.read(bytes);
            } while (length > 0);

            reader.close();

            connection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        }
        String repString = new String(buffer.toByteArray());
        //        System.err.println(repString);
        return repString;
    }

    //其他城市https请求
    public static String getOtherHttps(String urlString) {

        ByteArrayOutputStream buffer = new ByteArrayOutputStream(512);
        try {

            URL url = new URL(urlString);

            /*
             * use ignore host name verifier
             */
            HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("POST");// 网页提交方式“GET”、“POST”
            connection.setRequestProperty("Host", "app.api.lianjia.com");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Lianjia-Device-Id",
                "2A88A4C2-7949-4D98-85DC-8CA6359108AF");
            connection.setRequestProperty("Lianjia-Version", "7.2.0");
            connection.setRequestProperty("Lianjia-Timestamp", "1476951191.453009");
            connection.setRequestProperty("Accept-Language", "zh-Hans-CN;q=1");
            connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", "403");
            connection.setRequestProperty("User-Agent", "HomeLink 7.2.0;iPhone7,1;iOS 10.0.2;");
            connection.setRequestProperty("Authorization",
                "MjAxNjEwMDFfaW9zOjJhY2FlZjIwMDI4N2I3NjY0MThiYmZmN2UyZWFmMWJlNWNiMTM5ODU");
            connection.setRequestProperty("Connection", "keep-alive");
            connection.setRequestProperty("Page-Schema",
                "lianjia%3A%2F%2FLJSelecteCityViewController");
            connection
                .setRequestProperty(
                    "Cookie",
                    "lianjia_uuid=B04F3473-1166-4ECA-AE79-A469623301B9; lianjia_ssid=DB68F953-EB36-4368-B745-0754E86695C2; lianjia_udid=D5C33F3A-116B-4EA2-B7AA-3449C38711F5");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("contentType", "utf-8");

            connection.setRequestProperty("city_id", "120000");
            //connection.setRequestProperty("fields", "{\"hp_city_config\" : \"68c4f0817b1e1804f1cfa945b45a5e9e\",\"fangjia\" : \"\",\"hp_city_content\" : \"\"}");
            connection.setRequestProperty("request_ts", "1476961142");
            connection
                .setRequestProperty(
                    "params",
                    "{\"mobile_type\" : \"iOS\",\"is_format_deal_amount\" : 1,\"city_id\" : \"120000\",\"version\" : \"7.2.0\"}");

            // Prepare SSL Context
            TrustManager[] tm = { ignoreCertificationTrustManger };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());

            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(ssf);

            InputStream reader = connection.getInputStream();
            byte[] bytes = new byte[512];
            int length = reader.read(bytes);

            do {
                buffer.write(bytes, 0, length);
                length = reader.read(bytes);
            } while (length > 0);

            reader.close();

            connection.disconnect();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
        }
        String repString = new String(buffer.toByteArray());
        //        System.err.println(repString);
        return repString;
    }

    //获取http返回
    public static String getHttpReturn(String uri) throws Exception {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(uri);
        HttpResponse response = httpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() != 200) {
            return "error";
        }
        HttpEntity entity = response.getEntity();
        String res = EntityUtils.toString(entity);
        //        System.err.println(res);
        return res;
    }

}
